﻿using CyUSB;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinCyUSB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            USB_Init();
        }

        private USBDeviceList usbDevices = null; //定义USB设备列表
        private CyHidDevice MyDevice = null;
        public const ushort VID = 0x28E9;   //固定值 厂商ID（Vendor ID，简称VID）
        public const ushort PID = 0x128A;   //固定值 产品ID（Product ID，简称PID）
        /// <summary>
        /// USB 插入和拔出Event实例化
        /// </summary>
        private void USB_Init()
        {
            usbDevices = new USBDeviceList(CyConst.DEVICES_HID);
            usbDevices.DeviceAttached += new EventHandler(usbDevices_DeviceAttached);
            usbDevices.DeviceRemoved += new EventHandler(usbDevices_DeviceRemoved);
            foreach (USBDevice device in usbDevices)
            {
                if (device.VendorID == VID && device.ProductID == PID)
                {
                    MyDevice = usbDevices[VID, PID] as CyHidDevice; //实例化 myHidDevice设备，这样就可以对USBHID设备进行IN OUT操作
                    ConnInit(true);
                }
            }
        }

        //USB设备插入Event执行
        private void usbDevices_DeviceAttached(object sender, EventArgs e)
        {
            USBEventArgs ue = e as USBEventArgs;
            if (ue.VendorID == VID && ue.ProductID == PID)
            {
                ConnInit(true);
            }
        }

        //USB设备拔出Event执行
        private void usbDevices_DeviceRemoved(object sender, EventArgs e)
        {
            USBEventArgs ue = e as USBEventArgs;
            if (ue.VendorID == VID && ue.ProductID == PID)
            {
                ConnInit(false);
            }
        }
        /// <summary>
        /// 连接状态
        /// </summary>
        bool bConn = false;

        /// <summary>
        /// 连接状态
        /// </summary>
        /// <param name="isConnected"></param>
        private void ConnInit(bool isConnected)
        {
            bConn = isConnected;
            lblState.Text = bConn ? "连接成功" : "连接断开";
            PrintOriginal($"{DateTime.Now.ToLongTimeString()} {lblState.Text}\r\n");

            gbxBtn.Enabled = bConn;
        }

        private void PrintOriginal(string msg)
        {
            this.Invoke(new Action(() =>
            {
                txtLog.AppendText(msg);
            }));
        }
    }
}
